package com.heima.article.listen;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.service.ApArticleConfigService;
import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.article.pojos.ApArticleConfig;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class ArticleUpOrDownListener {
    @Autowired
    private ApArticleConfigService apArticleConfigService;

    @RabbitListener(queuesToDeclare = {@Queue(value = NewsUpOrDownConstants.NEWS_UP_FOR_ARTICLE_CONFIG_QUEUE)})
    public void newsUpHandler(@Payload String articleId, Message message, Channel channel){
        log.info("接收到自媒体文章上架的消息，文章id为:{}",articleId);
        try {
            //todo 当前消息路由
            apArticleConfigService.update(Wrappers.<ApArticleConfig>lambdaUpdate()
                    .set(ApArticleConfig::getIsDown,false)//false: 没有下架  0 ; true 下架   1
                    .eq(ApArticleConfig::getArticleId,Long.valueOf(articleId)));
            //todo 手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("article处理 自媒体文章上架消息 失败, 文章id: {}   原因: {}",articleId,e.getMessage());
        }

    }
    @RabbitListener(queuesToDeclare = {@Queue(value =NewsUpOrDownConstants. NEWS_DOWN_FOR_ARTICLE_CONFIG_QUEUE)})
    public void newsDownHandler(@Payload String articleId, Message message, Channel channel){

        log.info("接收到自媒体文章下架的消息，文章id为:{}",articleId);
        try {
            //todo 当前消息路由
            apArticleConfigService.update(Wrappers.<ApArticleConfig>lambdaUpdate()
                    .set(ApArticleConfig::getIsDown,true)
                    .eq(ApArticleConfig::getArticleId,Long.valueOf(articleId)));
            //todo 手动确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("article处理 自媒体文章下架消息 失败, 文章id: {}   原因: {}",articleId,e.getMessage());
        }
    }
}
